const std = @import("std");
const print = std.debug.print;

pub const Ipv4LpmKey = struct {
    prefixlen: u32,
    addr: [4]u8,
};

// 解析CIDR
pub fn parseCIDR(cidr: []const u8) !Ipv4LpmKey {
    var parts = std.mem.splitSequence(u8, cidr, "/");
    const addr_str = parts.next().?;
    const prefixlen_str = parts.next().?;

    var addr: [4]u8 = undefined;
    var i: usize = 0;
    var addr_parts = std.mem.splitSequence(u8, addr_str, ".");
    while (addr_parts.next()) |part| {
        addr[i] = try std.fmt.parseInt(u8, part, 10);
        i += 1;
    }
    const prefixlen = try std.fmt.parseInt(u32, prefixlen_str, 10);
    return Ipv4LpmKey{
        .prefixlen = prefixlen,
        .addr = addr,
    };
}

test "parseCIDR" {
    // print("{any}\n", .{@as([4]u8, [_]u8{ 127, 0, 0, 1 })});
    const key = try parseCIDR("192.168.1.0/24");
    try std.testing.expectEqual(@as(u8, 24), key.prefixlen);
    try std.testing.expectEqual(@as([4]u8, [_]u8{ 192, 168, 1, 0 }), key.addr);
}
